/*
 * $Id: CommandRefBuilderFactory.java,v 1.2 2009/08/20 21:37:36 navdeep_mahajan Exp $
 * 
 * Copyright (C) 2008 General Electric Company. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 * 
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */
package com.ge.healthcare.autosc.onwatch.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.onwatch.exception.CommandRefBuilderFactoryException;

public class CommandRefBuilderFactory {

	private static final String BASE_CMD_REFERENCE = "CMD";
	private static final String PRODIAGS_CMD_REFERENCE = "PD_CMD";

	public static ICommandRefBuilder getCommandRefBuilder(String content)
			throws CommandRefBuilderFactoryException {
		ICommandRefBuilder builder = null;
		if (isCommandTypeMatch(content, PRODIAGS_CMD_REFERENCE)) {
			builder = new ProdiagsCommandRefBuilder();
		} else if (isCommandTypeMatch(content, BASE_CMD_REFERENCE)) {
			builder = new BaseCommandRefBuilder();
		} else {
			// no reference, everything is fine
		}
		return builder;
	}

	private static boolean isCommandTypeMatch(String content, String cmdType)
			throws CommandRefBuilderFactoryException {
		String methodName = "isCommandTypeMatch";
		boolean match = false;
		try {
			BufferedReader reader = new BufferedReader(
					new StringReader(content));
			String line = null;
			// Read content one line at a line as content cannot be too long for
			// RE
			RE nameSub = new RE("^(.*)%REF:" + cmdType + ":(.*):REF%(.*)$");
			while ((line = reader.readLine()) != null) {
				if (nameSub.match(line)) {
					ASCLogger.info(CommandRefBuilderFactory.class, methodName,
							"Content contains command type " + cmdType, true);
					match = true;
					break;
				}
			}
		} catch (IOException ioe) {
			throw new CommandRefBuilderFactoryException(
					"Failed reading content " + content, ioe);
		} catch (RESyntaxException reException) {
			throw new CommandRefBuilderFactoryException(
					"Failed performing RE Conversion", reException,
					OnWatchCodeConstants.PRC_F_OWR_031);
		}
		return match;
	}
}
